package com.example.demo.service.impl;


import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.LoginUser;
import com.example.demo.entity.Result;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.service.LoginService;
import com.example.demo.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    public Result login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getAccount(),user.getPassword());
        //AuthenticationManger authenticate进行用户认证,
        //用户信息封装成Authentication作为authenticate（）方法参数
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //认证失败，给出提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户认证失败");
        }
        //获取用户信息UserDetails,LoginUser实现了UserDetails接口
        LoginUser principal = (LoginUser) authenticate.getPrincipal();
        //认证通过，用户信息生成token
        Map<String, String> params = new HashMap<>();
        params.put("account", principal.getUser().get("account").toString());
        params.put("username", principal.getUser().get("username").toString());
        String token = JWTUtil.getToken(params);
        //把User信息存入redis中，减少数据库查询操作,存入LogingUser会造成redis获取时JSON格式转换失效
        redisTemplate.opsForValue().set("login:"+principal.getUser().get("account").toString(),principal);
        //返回前端数据token和用户信息
        Map<String, Object> params1 = new HashMap<>();
        params1.put("token",token);
        params1.put("userInfo",principal.getUser());
        return Result.ok(params1);
    }

    @Override
    public Result logout() {
        //SecurityContextHolder.getContext().getAuthentication()获取安全上下文获取Authentication对象
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String redisKey="login:"+loginUser.getUser().get("account");
        redisTemplate.delete(redisKey);
        return Result.ok("退出成功");
    }

    @Override
    public Result checkToken(HttpServletRequest request) {
        String token = request.getHeader("token").toString();
        try {
            JWTUtil.verity(token);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("403","用户不合法");
        }
        return Result.OK_EMPTY;
    }
}
